<?php

namespace App\Http\Middleware;

use App\Logic\AdminUser as LogicAdminUser;
use App\Models\AdminUser;
use App\Utils\Code;
use Closure;

class AdminAuth
{
    /**
     * 处理传入的请求
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $path = $request->path();
        if (!$token = $request -> header('token')) {
            echo json_encode(renderError(Code::TOKEN_IS_EMPTY)); 
            exit;
        }

        // token验证
        $adminUser = new AdminUser;
        $userInfo = $adminUser -> tokenToInfo($token);
        if (!$userInfo) {
            echo json_encode(renderError(Code::TOKEN_IS_EXPIRE));
            exit;
        }
        $request -> attributes -> add(['user_info' => $userInfo]);

        // 接口权限验证
        // $logicUser = new LogicAdminUser;
        // $nodeList = $logicUser -> apiNodeList($userInfo['menu_ids'] ?? '');
        // if (!in_array($path, $nodeList)) {
        //     echo json_encode(renderError(Code::IS_NOT_OPRATE_AUTH));
        //     exit;
        // }

        return $next($request);
    }
}